package com.draven.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.draven.mall.entity.Category;
import com.draven.mall.mapper.CategoryMapper;
import com.draven.mall.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品分类服务实现类
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public List<Category> getAllCategories() {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSortOrder);
        return list(queryWrapper);
    }

    @Override
    public List<Category> getCategoryTree() {
        List<Category> allCategories = getAllCategories();
        // 构建树形结构
        return buildCategoryTree(allCategories);
    }

    @Override
    public Category getCategoryById(Long id) {
        return getById(id);
    }

    @Override
    @Transactional
    public boolean addCategory(Category category) {
        return save(category);
    }

    @Override
    @Transactional
    public boolean updateCategory(Category category) {
        return updateById(category);
    }

    @Override
    @Transactional
    public boolean deleteCategory(Long id) {
        // 检查是否有子分类
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getParentId, id);
        long count = count(queryWrapper);
        if (count > 0) {
            return false; // 有子分类不能删除
        }
        
        return removeById(id);
    }

    @Override
    @Transactional
    public boolean updateCategoryStatus(Long id, Integer status) {
        LambdaUpdateWrapper<Category> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Category::getId, id).set(Category::getStatus, status);
        return update(updateWrapper);
    }

    /**
     * 构建树形分类结构
     */
    private List<Category> buildCategoryTree(List<Category> allCategories) {
        // 获取所有顶级分类
        List<Category> rootCategories = allCategories.stream()
                .filter(category -> category.getParentId() == 0 || category.getParentId() == null)
                .sorted(Comparator.comparing(Category::getSortOrder))
                .collect(Collectors.toList());

        // 为每个顶级分类设置子分类
        rootCategories.forEach(root -> {
            root.setChildren(getChildCategories(root, allCategories));
        });

        return rootCategories;
    }

    /**
     * 递归获取子分类
     */
    private List<Category> getChildCategories(Category parent, List<Category> allCategories) {
        List<Category> childCategories = allCategories.stream()
                .filter(category -> parent.getId().equals(category.getParentId()))
                .sorted(Comparator.comparing(Category::getSortOrder))
                .collect(Collectors.toList());

        // 递归设置子分类的子分类
        childCategories.forEach(child -> {
            child.setChildren(getChildCategories(child, allCategories));
        });

        return childCategories.isEmpty() ? null : childCategories;
    }
} 